# 导入selenium模块
import os.path
import random
from selenium import webdriver
import datetime
from time import sleep
from selenium.webdriver.common.by import By
from 自动化流程测试.招募结算一体流程.createSettleExcel import create_settlement_template
from reClick import click_element

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def isPending(pay_status,driver,excel_name):
    counter = 0 #初始化循环计数器
    commitCounter = 0 #初始化循环计数器
    errorCount = 0
    while True:
        try:
            wait = WebDriverWait(driver, 3)  # 等待1秒再检查
            sleep(7)
            #选中上传的结算单
            wait.until(EC.presence_of_element_located((By.XPATH, f'//div[@class="title" and contains(text(), "{excel_name}")]'))).click()
            # 等待元素出现
            sleep(5)
            #获取列表中的支付状态
            spans = driver.find_elements(By.CSS_SELECTOR,'.el-tag')
            name = []
            for span in spans:
                name.append(span.text)
            print(name)
            if '提交中' in name:
                commitCounter += 1
                print('循环执行，获取支付结果，目前提交中出现' + str(commitCounter) + '次')
                if commitCounter == 10:
                    print('已循环10次，未出现支付中，当前流程结束')
                    return True
            if '支付中' in name and '支付成功' not in name:
                counter += 1
                print('循环执行，获取支付结果，目前支付中出现' + str(counter) + '次')
                if counter == 5:
                    print('已循环五次，未出现支付完成，流程结束，支付结果请自行关注')
                    break
            if pay_status in name :
                break  # 如果value是'待支付'、‘支付成功’，跳出循环，开始后续流程
            else:
                num = 30
                print('Value is not ' + pay_status + f', waiting for {num} seconds...')
                print('考虑结算单提交流程的耗时，等待30秒')
                sleep(num)
        except Exception as e:
            print(f"An error occurred: {e}")
            errorCount += 1
            if errorCount == 3:
                print('连续出现三次错误，流程结束')
                return True


def run_automation_flow(username,password,pay_password,url,dept_name,type):

    # chrome_options = Options()
    # chrome_options.add_argument('--headless')
    # chrome_options.add_argument('--disable-gpu')
    # options=chrome_options
    # 启动浏览器驱动
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.implicitly_wait(10)
    # 访问url
    driver.get(url)

    # 定位元素，执行自动化操作--填充账号信息
    sleep(1)
    click_element(driver,'NAME',1,'username',f'填充账号{username}',username)

    # 执行自动化操作--填充密码信息
    sleep(1)
    click_element(driver,'NAME',1,'password',f'填充密码{password}',password)

    #定位验证码，验证码已取消，填充默认值
    sleep(1)
    driver.find_element(By.NAME, 'code').send_keys('1234')

    #登录点击事件
    click_element(driver,'XPATH',1,'//*[@id="pane-bindLogin"]/button','登录点击事件',None)

    #点击结算管理菜单
    click_element(driver,'XPATH',1,'//*[@id="app"]/div/div[1]/div[2]/div[1]/div/ul/div[5]/li/div','点击结算管理菜单',None)

    #点击快速支付菜单
    click_element(driver,'XPATH',1,'//*[@id="app"]/div/div[1]/div[2]/div[1]/div/ul/div[5]/li/ul/div[1]/a/li','点击快速支付菜单',None)

    #快速支付菜单 -- 点击上传结算单按钮
    click_element(driver,'CLASS_NAME',1,'btnupload','点击上传结算单按钮',None)


    #快速支付菜单 -- 选择结算任务
    click_element(driver,'XPATH',1,'//*[@id="app"]/div/div[2]/section/div[2]/div[2]/div/div[2]/div[4]/div/div/div[2]/div[1]/div[2]/div/form/div/div[3]/table/tbody/tr','选择结算任务',None)
    #快速支付菜单 -- 选择结算任务 -- 点击确定
    click_element(driver,'CLASS_NAME',1,'confirmBtn','选择结算任务 -- 点击确定',None)


    #生成excel文件，返回全路径地址
    excelPath = create_settlement_template(type,dept_name)

    #将文件路径填入上传框\
    sleep(2)
    try:
        driver.find_element(By.XPATH,'//*[@id="app"]/div/div[2]/section/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/div[2]/div[2]/form/div[2]/div/div[1]/button/span/input').send_keys(excelPath)
    except Exception:
        driver.find_element(By.XPATH,'//*[@id="app"]/div/div[2]/section/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/div[2]/div[2]/form/div[2]/div/div[1]/button/span/input').send_keys(excelPath)

    sleep(3)
    #上传结算单 -- 点击上传按钮
    click_element(driver,'XPATH',1,'//*[@id="app"]/div/div[2]/section/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/div[2]/div[3]/div[2]/button[2]','上传结算单 -- 点击上传按钮',None)


    #选择导入成功的结算单
    click_element(driver,'XPATH',10,'//*[@id="app"]/div/div[2]/section/div[2]/div[1]/div/div/div[3]/div[1]','选择导入成功的结算单',None)

    excel_name = os.path.splitext(os.path.basename(excelPath))[0]
    print('结算单名称为：' + excel_name)
    boolean = isPending('待支付',driver,excel_name)
    if boolean:
        driver.quit()
    #点击全部支付
    sleep(10)
    click_element(driver,'XPATH',10,'//*[@id="app"]/div/div[2]/section/div[2]/div[2]/div/div[1]/div[2]/div/div[1]/div[1]/button[2]','点击全部支付',None)

    #点击支付按钮
    click_element(driver,'XPATH',1,'//*[@id="app"]/div/div[2]/section/div[2]/div[3]/button','点击支付按钮',None)

    #填充支付密码
    click_element(driver,'ID',1,'payPassword','填充支付密码',pay_password)

    #点击确认支付
    click_element(driver,'ID',1,'payPasswordBtn','点击确认支付',None)
    sleep(3)
    isPending('支付成功',driver,excel_name)
    sleep(5)
    driver.quit()


def recurrent_execution(username,password,pay_password,url,dept_name,type):
    count = 0
    # 新增一个循环，每15分钟执行一次
    while True:
        try:
            run_automation_flow(username,password,pay_password,url,dept_name,type)
            num_rows = random.randint(300, 600) #随机五到十分钟执行一次
            min = num_rows/60
            formatted_time = datetime.datetime.now() + datetime.timedelta(minutes=min)
            formatted_time_str = formatted_time.strftime('%Y-%m-%d %H:%M:%S')
            count += 1
            print(f"{username}执行第{count}次")
            print(f"等待{min:.0f}分钟，下一次执行将在{formatted_time_str}")
            sleep(num_rows)  # 15分钟 = 900秒
        except Exception as e:
            print(f"An error occurred: {e}")
            sleep(60)  # 在发生错误时，等待1分钟再重试